import {returnValueHandlerContainer} from "../containers/returnValueHandlerContainer"
import {ReturnValueHandlerNotFoundException} from "../exception/ReturnValueHandlerNotFoundException"

export class ReturnValueHandlerManager {

  static handlerList = returnValueHandlerContainer

  static resolveReturnValueHandler = (Ctor: any) => {
    const instance = new Ctor()
    instance.__order = Ctor.__order || 0
    ReturnValueHandlerManager.handlerList.push(instance)
  }

  private static getSortedHandlerList() {
    // @ts-ignore
    return ReturnValueHandlerManager.handlerList.sort((a, b) => b.__order - a.__order)
  }

  resolveReturnValue(req: HttpRequest, res: HttpResponse, value: any) {
    const handler = ReturnValueHandlerManager.getSortedHandlerList().find(i => i.canWrite(value))
    if(!handler) {
      throw new ReturnValueHandlerNotFoundException("can not find returnValueHandler for type:" + typeof value)
    }
    handler.write(req, res, value)
  }
}
